package com.Policing.Back;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;

import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.*;

import com.Policing.Since_case.Since_case;
import com.Policing.misc.Accompaniment;
import com.Policing.uhf.util.DataTransfer;
import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnDismissListener;
import com.bigkoo.alertview.OnItemClickListener;
import com.Policing.Adapter.Input_Adapter_item;
import com.Policing.Ip_set.Ip_Set;
import com.Policing.R;
import com.Policing.Scan.qrcode.util.Constant;
import com.Policing.Scan.zxing.activity.CaptureActivity;
import com.Policing.CanniBalize.Shift_site;
import com.Policing.bean.Input_item;

import com.senter.iot.support.openapi.uhf.UhfD2;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Administrator on 2018/12/25.
 */

public class back extends Activity implements OnDismissListener {
    private ImageView imageView;
    private TextView site_tv,title_text;
    private String site_id="";
    private String url="http://"+ Ip_Set.IP+"/api/returnsAddInspect";
    private String urls="http://"+ Ip_Set.IP+"/api/returnsUserInspect";
    private String rfid_url="http://"+ Ip_Set.IP+"/api/returnsAdd";
    private ListView lv_list;
    private LinearLayout site;
    private Button uploads,bt_Rfid;
    private Button scan_img;//扫码
    private List<Input_item> data = new ArrayList<>();
    private List<String> rfid_data = new ArrayList<>();
    private List<String> userids = new ArrayList<>();

    private String id;
    private List<String> numbers = new ArrayList<>();//资产ID
    private Activity content;
    private EditText et_num;
    private Handler handler = new Handler();
    private List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
    private boolean state;
    private final Accompaniment accompaniment = Accompaniment.newInstanceOfResource(back.this, R.raw.tag_inventoried);
    //播放声音
    private Handler accompainimentsHandler;
    private final Runnable accompainimentRunnable = new Runnable() {
        @Override
        public void run() {
            accompaniment.start();
            accompainimentsHandler.removeCallbacks(this);
        }
    };
    private boolean isrfid=true;
    private boolean stop_rfid =true;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.back);
        HandlerThread htHandlerThread = new HandlerThread("");
        htHandlerThread.start();
        accompainimentsHandler = new Handler(htHandlerThread.getLooper());
        content = this;
        SharedPreferences mm = getSharedPreferences("mm", Context.MODE_PRIVATE);//1.通过上下文得到
        id = mm.getString("id","");
        data.clear();
        init();
    }

    private void init() {
        et_num = (EditText) findViewById(R.id.et_num);
        title_text = (TextView) findViewById(R.id.title_text);
        title_text.setText("归还");
        site_tv = (TextView) findViewById(R.id.site_tv);
        site = (LinearLayout)findViewById(R.id.site);
        site.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(content, Shift_site.class);
                startActivityForResult(intent,3);
            }
        });
        bt_Rfid = (Button) findViewById(R.id.Rfid);
        uploads = (Button) findViewById(R.id.add);
        uploads.setText("归还");
        lv_list = (ListView) findViewById(R.id.fragment2_list);
        //给链表添加数据
        //List<Map<String, Object>> list=getData();
        //适配器，刚刚重写的！
        //MyAdapter myAdapter = new MyAdapter(getActivity(), list);
        //设置适配器
        //lv_list.setAdapter(myAdapter);
        scan_img = (Button) findViewById(R.id.scan_img);
        scan_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               startQrCode();

            }
        });
        imageView = (ImageView) findViewById(R.id.fh);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        et_num.setInputType(InputType.TYPE_NULL);
        et_num.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }
            @Override
            public void afterTextChanged(Editable S) {
                et_num.selectAll();
                if (!et_num.getText().toString().trim().equals("")){
                        posts(et_num.getText().toString().trim(), "");
                }else {
                    Toast.makeText(back.this,"错误的格式",Toast.LENGTH_SHORT).show();
                }
            }
        });
        et_num.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                et_num.selectAll();
            }
        });
        lv_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int i, long id) {
                new AlertView(" 提示！", "是否删除", "取消",new String[]{"确定"}, null, content, AlertView.Style.Alert, new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int position) {
                        //取消：position=-1,确定 position=0
                        if (position==0){
                            data.remove(i);
                            Input_Adapter_item adapter_item = new Input_Adapter_item(content,R.layout.input_adapter_item,data);
                            lv_list.setAdapter(adapter_item);
                        }
                        if (position==-1){

                        }

                    }
                }).setCancelable(true).setOnDismissListener(back.this).show();
            }
        });
        uploads.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (data.size()<=0){
                    Toast.makeText(content,"请扫码需要归还的资产",Toast.LENGTH_SHORT).show();
                    return;
                }
                if (site_id.equals("")){
                    Toast.makeText(content,"请选择存放位置后上传",Toast.LENGTH_SHORT).show();
                    return;
                }
                new AlertView(" 提示！", "是否上传数据", "取消",new String[]{"确定"}, null, content, AlertView.Style.Alert, new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int position) {
                        //取消：position=-1,确定 position=0
                        if (position==0){
                            numbers.clear();
                            for (int i =0;i<data.size();i++){
                                numbers.add(data.get(i).getCode_number());
                                userids.add(data.get(i).getRfid());
                            }
                            updata();
                        }
                        if (position==-1){

                        }

                    }
                }).setCancelable(true).setOnDismissListener(back.this).show();

            }
        });
        bt_Rfid.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if (isrfid==true){
                        if (UhfD2.getInstance().init() == true){
                            UhfD2.getInstance().iso18k6cSetAccessEpcMatch(UhfD2.UmdEpcMatchSetting.newInstanceOfDisable());
                        }
                        isrfid = false;
                    }

                }catch (Exception E){
                    Toast.makeText(back.this,"没有RFID模块",Toast.LENGTH_SHORT).show();
                    return;
                }
                if (stop_rfid){
                    stop_rfid=false;
                    start_read();
                    bt_Rfid.setText("停止读取");
                }else {
                    stop_rfid=true;
                    state =false;
                    bt_Rfid.setText("开启RFID");
                }

            }
        });

    }

    public void posts(final String assetNumber, final String userid) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象。
                FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
                formBody.add("assetNumber",assetNumber)
                        .add("id",id)
                        .add("source", Since_case.set().getSource())
                        .add("userId",userid); //传递键值对参数
                Request request = new Request.Builder()//创建Request 对象。
                        .url(url)
                        .post(formBody.build())//传递请求体
                        .build();
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        //回调方法的使用与get异步请求相同
                        Log.i("123123", "error");
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        final String responseData = response.body().string();
                        //回调方法的使用与get异步请求相同
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    Bitmap bitmap =null;
                                    Log.i("123123", responseData);
                                    JSONObject json = new JSONObject(responseData);
                                    if (json.getString("state").equals("1"))
                                    {
                                        JSONObject jsonObject = json.getJSONObject("asset");
                                        String assetName = jsonObject.getString("assetName");
                                        String deptId = jsonObject.getString("deptId");
                                        String assetNumber = jsonObject.getString("assetNumber");
                                        String userId = jsonObject.getString("userId");
                                        String model = jsonObject.getString("model");
                                        String type = jsonObject.getString("type");
                                    //    String rfid = jsonObject.getString("rfid");
                                        if (jsonObject.getString("image").equals("")){
                                           /* InputStream is = getResources().openRawResource(R.mipmap.null_po);
                                            bitmap = BitmapFactory.decodeStream(is);*/
                                        }else {
                                            byte [] input = Base64.decode(jsonObject.getString("image"), Base64.DEFAULT);
                                            bitmap = BitmapFactory.decodeByteArray(input, 0, input.length);
                                        }
                                        Collections.reverse(data);
                                        data.add(new Input_item(bitmap,assetName,deptId,assetNumber,userId,model,type,userid));
                                        Collections.reverse(data);
                                        Input_Adapter_item adapter_item = new Input_Adapter_item(content,R.layout.input_adapter_item,data);
                                        lv_list.setAdapter(adapter_item);
                                        Toast.makeText(content,"添加成功",Toast.LENGTH_SHORT).show();

                                    }
                                    if (json.getString("state").equals("0")){

                                        Toast.makeText(content,"添加失败",Toast.LENGTH_SHORT).show();

                                    }
                                    if (json.getString("state").equals("2")){

                                        Toast.makeText(content,"此资产不属于当前用户！",Toast.LENGTH_SHORT).show();
                                    }
                                    if (json.getString("state").equals("3")){
                                        et_num.selectAll();
                                        Toast.makeText(content,"添加失败，此资产已申请归还",Toast.LENGTH_SHORT).show();

                                    }
                                    if (json.getString("state").equals("4")){
                                        et_num.selectAll();
                                        Toast.makeText(content,"添加失败，此资产不是在用状态",Toast.LENGTH_SHORT).show();

                                    }

                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }


                            }
                        });

                    }
                });

            }
        }).start();

    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent datas) {
        super.onActivityResult(requestCode, resultCode, datas);
        /* if (requestCode==6&&resultCode==1){
            if (!data.getStringExtra("data").equals("")){
                rfid_data = data.getStringExtra("data");
                updata();
            }

        }*/
     /*   if (requestCode==7&&resultCode==7){
            posts(datas.getExtras().getString("assetNumber"), datas.getExtras().getString("admin_id"));
        }*/
        if (requestCode==3&&resultCode==3){
            site_tv.setText(datas.getExtras().getString("site_name"));
            site_id = datas.getExtras().getString("site_id");
            Log.i("333333333333",site_id);
        }
        //扫描结果回调
        if (requestCode == Constant.REQ_QR_CODE && resultCode == RESULT_OK) {
            Bundle bundle = datas.getExtras();
            String scanResult = bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN);
            //将扫描出的信息显示出来
            //property_one.setText(scanResult);
          /*  for (int i = 0; i<data.size();i++){
                if (scanResult.equals(data.get(i).getCode_number())){
                    Toast.makeText(back.this,"此资产已盘点",Toast.LENGTH_SHORT).show();
                    return;
                }
            }*/
            posts(scanResult,"");


        }
    }

    private void updata() {
        new Thread(){
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    RequestBody requestBody = new FormBody.Builder()
                            .add("userIds",userids.toString())
                            .add("place",site_id)
                            .add("id",id)
                            .add("source",Since_case.set().getSource())
                            .add("assetNumbers",numbers.toString())
                            .build();
                    Request request = new Request.Builder()
                            .url(rfid_url)
                            .post(requestBody).build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    showResponse(responseData);
                    Log.i("222",responseData);
                } catch (IOException e) {
                    e.printStackTrace();
                }



            }
        }.start();
    }

    private void showResponse(final String responseData) {
       runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    JSONObject jsonObject = new JSONObject(responseData);
                    if (jsonObject.getString("state").equals("1")){
                        data.clear();
                        numbers.clear();
                        Input_Adapter_item adapter_item = new Input_Adapter_item(content,R.layout.input_adapter_item,data);
                        lv_list.setAdapter(adapter_item);
                        Toast.makeText(content,"提交成功",Toast.LENGTH_SHORT).show();
                        finish();
                    }else {
                        Toast.makeText(content,"提交失败,请重新提交",Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    private void startQrCode() {
        // 申请相机权限
        if (ActivityCompat.checkSelfPermission(content, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // 申请权限
            ActivityCompat.requestPermissions(content, new String[]{Manifest.permission.CAMERA}, Constant.REQ_PERM_CAMERA);
            return;
        }
        // 申请文件读写权限（部分朋友遇到相册选图需要读写权限的情况，这里一并写一下）
        if (ActivityCompat.checkSelfPermission(content, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            // 申请权限
            ActivityCompat.requestPermissions(content, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, Constant.REQ_PERM_EXTERNAL_STORAGE);
            return;
        }
        // 二维码扫码
        Intent intent = new Intent(content, CaptureActivity.class);
        startActivityForResult(intent, Constant.REQ_QR_CODE);
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case Constant.REQ_PERM_CAMERA:
                // 摄像头权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获得授权
                    startQrCode();
                } else {
                    // 被禁止授权
                    Toast.makeText(content, "请至权限中心打开本应用的相机访问权限", Toast.LENGTH_LONG).show();
                }
                break;
            case Constant.REQ_PERM_EXTERNAL_STORAGE:
                // 文件读写权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获得授权
                    startQrCode();
                } else {
                    // 被禁止授权
                    Toast.makeText(content, "请至权限中心打开本应用的文件读写权限", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }
    private void start_read(){
        state=true;
        UhfD2.getInstance().iso18k6cRealTimeInventory(1, new UhfD2.UmdOnIso18k6cRealTimeInventory() {
            @Override
            public void onTagInventory(UhfD2.UII uii, UhfD2.UmdFrequencyPoint umdFrequencyPoint, Integer integer, UhfD2.UmdRssi umdRssi) {
                for (int i = 0; i<data.size();i++){
                    if (DataTransfer.xGetString(uii.getBytes()).replace(" ","").substring(4).equals(data.get(i).getRfid())){
                        return;
                    }
                }
                if (!rfid_data.contains(DataTransfer.xGetString(uii.getBytes()).replace(" ","").substring(4))){
                    rfid_data.add(DataTransfer.xGetString(uii.getBytes()).replace(" ","").substring(4));
                    final String rfid = DataTransfer.xGetString(uii.getBytes()).replace(" ","").substring(4);
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {

                            //posts("",rfid);


                        }
                    },500);
                    trigTagAccompainiment();//播放声音
                }
            }

            @Override
            public void onFinishedSuccessfully(Integer integer, int i, int i1) {
                onFinishedOnce();
            }
            private void onFinishedOnce() {
                if (state) {
                    start_read();
                }
            }
            @Override
            public void onFinishedWithError(UhfD2.UmdErrorCode umdErrorCode) {
                onFinishedOnce();
            }
        });


    }
    @Override
    public void onDismiss(Object o) {

    }
    private void trigTagAccompainiment() {
        accompainimentsHandler.post(accompainimentRunnable);
    }
    @Override
    protected void onDestroy() {
        if (accompainimentsHandler != null) {
            accompainimentsHandler.getLooper().quit();
        }
        accompaniment.release();
        stop_rfid=false;
        try {
            UhfD2.getInstance().uninit();
        }catch (Exception e){
        }

        super.onDestroy();
    }
 /*   private void Thread1(final String assetNumber) {
        Map<String,String> map = new HashMap<>();
        map.put("id",id);
        map.put("assetNumber",assetNumber);
        HttpOkHttp.getInstance().requestPost(urls, map, new HttpOkHttp.OkHttpCallBack<String>() {
            @Override
            public void requestSuccess(String  responseData) {
                try {
                    JSONObject jsonObject = new JSONObject(responseData);
                    if (jsonObject.getString("state").equals("1")){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Intent intent = new Intent(back.this,userbackQuery.class);
                    intent.putExtra("assetNumber",assetNumber);
                    startActivityForResult(intent,7);
                }
            });
                    }else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                et_num.selectAll();
                                Toast.makeText(back.this,"此编码无在用资产",Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void requestFailure(String message) {

            }
        },String.class);
    }*/
}
